import datetime
# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins, viewsets, status, permissions
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import filters

from carts.models import CartRe
from goods.models import GoodsCategory, Brand, HotSearchWords, Goods, Banner, DiscountPackage, SearchAd, GoodsAttribute, \
    GoodsBannerImage, GoodsDescImage
from goods.serializers import GoodsBrandSerializer
from operator_goods.serializers import CategorySerializer, HotWordsSerializer, GoodsSerializer, \
    BannerSerializer, DiscountPackageSerializer, SearchAdSerializer, NewGoodsSerializer, HotGoodsSerializer, \
    HighpointGoodsSerializer, CartReSerializer, OptGoodsSerializer, GoodsListSerializer, GoodsAttributeSerializer, \
    GoodsBannerImageSerializer, GoodsDescImageSerializer
from operator_utils.permissions import AdminAuth


class BaseViewset(ModelViewSet):
    """增删查改基类"""

    permission_classes = (AdminAuth,)

    def destroy(self, request, *args, **kwargs):
        # 软删除
        instance = self.get_object()
        instance.is_delete = True
        instance.save()
        return Response(data={'msg': '删除成功！'}, status=status.HTTP_204_NO_CONTENT)


class GoodsPagination(PageNumberPagination):
    page_size = 9
    # page_size = 2
    # 向后台要多少条
    page_size_query_param = 'page_size'
    # 定制多少页的参数
    page_query_param = "page"
    max_page_size = 100


class CategoryOperateViewset(BaseViewset):
    """商品分类的增删查改"""
    queryset = GoodsCategory.objects.filter(is_delete=False)
    serializer_class = CategorySerializer
    # 设置三大常用过滤器之DjangoFilterBackend, SearchFilter
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    # 设置我们的search字段
    search_fields = ('name',)

    def create(self, request, *args, **kwargs):
        # 限制不能添加重复的类别名
        name = request.data.get('name')
        queryset = self.queryset.filter(name=name).first()
        if queryset:
            return Response(data={'msg': '不能添加重复的类别名'}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
        return super().create(request)


class CategoryIndexOperateViewset(mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """商品分类首页显示"""
    queryset = GoodsCategory.objects.filter(is_delete=False)
    serializer_class = CategorySerializer

    def update(self, request, *args, **kwargs):
        # 重写，只能修改is_index字段的值
        is_index = request.data.get('is_index')
        instance = self.get_object()
        instance.is_index = is_index
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class BrandOperateViewset(BaseViewset):
    """商品品牌的增删查改"""
    queryset = Brand.objects.filter(is_delete=False)
    serializer_class = GoodsBrandSerializer
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)

    def create(self, request, *args, **kwargs):
        # 限制不能添加重复的品牌名
        name = request.data.get('name')
        queryset = self.queryset.filter(name=name).first()
        if queryset:
            return Response(data={'msg': '不能添加重复的类别名'}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
        return super().create(request)


class HotSearchWordsOperateViewset(ModelViewSet):
    """搜索栏下方热搜词的增删查改"""
    queryset = HotSearchWords.objects.all()
    serializer_class = HotWordsSerializer
    permission_classes = (AdminAuth,)


class BannerOperateViewset(ModelViewSet):
    """首页轮播图的增删查改"""
    queryset = Banner.objects.filter(is_delete=False)
    serializer_class = BannerSerializer
    permission_classes = (AdminAuth,)

    def create(self, request, *args, **kwargs):
        # 首页轮播图限制6张
        if self.queryset.count() > 6: return Response(status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
        return mixins.CreateModelMixin.create(self, request, *args, **kwargs)


class DiscountOptnewGoodsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """优惠套餐左侧可选商品"""
    serializer_class = OptGoodsSerializer
    queryset = Goods.objects.filter(goods_status=1, is_delete=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)


class DiscountOperateViewset(BaseViewset):
    """优惠套餐的增删查改"""
    queryset = DiscountPackage.objects.filter(is_delete=False)
    serializer_class = DiscountPackageSerializer
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name', 'goods__name')

    def list(self, request, *args, **kwargs):
        today = datetime.date.today()
        queryset = DiscountPackage.objects.all()
        for i in queryset:
            for j in i.goods.all():
                # 如果当前时间在套餐的有效期内，那么该套餐生效
                if i.start_time <= today <= i.end_time:
                    i.is_valid = True
                    i.save()
                # 如果套餐中有一个或多个商品下架或者超出活动时间，那么该套餐失效
                if j.goods_status == 0 or today >= i.end_time:
                    i.is_valid = False
                    i.save()
        return super().list(request)


class DiscounMenuViewset(mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """套餐列表页切换按钮"""
    queryset = DiscountPackage.objects.filter(is_delete=False)
    serializer_class = DiscountPackageSerializer

    def update(self, request, *args, **kwargs):
        # 重写，只能修改is_valid字段的值
        is_valid = request.data.get('is_valid')
        today = datetime.date.today()
        instance = self.get_object()
        if is_valid == True and instance.end_time < today:
            return Response(data={'msg': '当前时间已超过活动截止时间，无法修改'}, status=status.HTTP_409_CONFLICT)
        instance.is_valid = is_valid
        if is_valid == True:
            instance.start_time = today
        if is_valid == False and instance.start_time < today:
            instance.end_time = today
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class SearchAdViewset(ModelViewSet):
    """搜索框下方广告的增删查改"""
    queryset = SearchAd.objects.all()
    serializer_class = SearchAdSerializer
    permission_classes = (AdminAuth,)

    def create(self, request, *args, **kwargs):
        # 限制搜索框下方广告只能添加一个,添加的同时会删掉以前的广告
        if self.queryset.count() >= 1:
            self.queryset.delete()
        return mixins.CreateModelMixin.create(self, request, *args, **kwargs)


class NewOptnewGoodsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """新品专享左侧可选商品"""
    serializer_class = OptGoodsSerializer
    queryset = Goods.objects.filter(goods_status=1, is_delete=False, is_new=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)


class NewGoodsViewSet(BaseViewset):
    """新品专享的是否上线"""
    serializer_class = NewGoodsSerializer
    pagination_class = GoodsPagination
    queryset = Goods.objects.filter(goods_status=1, is_delete=False, is_new=True).order_by('-start_time')
    ordering_fields = ('sold_num', 'shop_price')
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)
    filter_fields = ('is_new',)

    def create(self, request, *args, **kwargs):
        # 添加新品
        goods_list = request.data.get('goods_list')
        for goods_id in goods_list:
            try:
                goods = Goods.objects.filter(id=goods_id, is_delete=False, is_new=False).first()
            except Exception as e:
                return Response(data={'msg': '输入有误/商品不存在/该商品已是新品'}, status=status.HTTP_204_NO_CONTENT)
            if goods:
                goods.is_new = True
                goods.save()
        return self.list(request)

    def update(self, request, *args, **kwargs):
        # 重写，只能修改is_new字段的值
        is_new = request.data.get('is_new')
        instance = self.get_object()
        instance.is_new = is_new
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        return Response(data={'msg': '操作不允许'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)


class HotOptnewGoodsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """热销左侧可选商品"""
    serializer_class = OptGoodsSerializer
    queryset = Goods.objects.filter(goods_status=1, is_delete=False, is_hot=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)


class HotGoodsViewSet(BaseViewset):
    """热销榜的是否上线"""
    serializer_class = HotGoodsSerializer
    pagination_class = GoodsPagination
    queryset = Goods.objects.filter(is_delete=False, goods_status=1, is_hot=True).order_by('-start_time')
    ordering_fields = ('sold_num', 'shop_price')
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)
    filter_fields = ('is_hot',)

    def create(self, request, *args, **kwargs):
        # 添加至热销榜
        goods_list = request.data.get('goods_list')
        for goods_id in goods_list:
            try:
                goods = Goods.objects.filter(id=goods_id, is_delete=False, is_hot=False).first()
            except Exception as e:
                return Response(data={'msg': '输入有误/商品不存在/该商品已是热销品'}, status=status.HTTP_204_NO_CONTENT)
            if goods:
                goods.is_hot = True
                goods.save()
        return self.list(request)

    def update(self, request, *args, **kwargs):
        # 重写，只能修改is_hot字段的值
        is_hot = request.data.get('is_hot')
        instance = self.get_object()
        instance.is_hot = is_hot
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        return Response(data={'msg': '操作不允许'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)


class HighpointOptnewGoodsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """高端左侧可选商品"""
    serializer_class = OptGoodsSerializer
    queryset = Goods.objects.filter(goods_status=1, is_highpoint=False, is_delete=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)


class HighpointGoodsViewSet(BaseViewset):
    """高端榜的是否上线"""
    serializer_class = HighpointGoodsSerializer
    pagination_class = GoodsPagination
    queryset = Goods.objects.filter(is_delete=False, goods_status=1, is_highpoint=True).order_by('-start_time')
    ordering_fields = ('sold_num', 'shop_price')
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)
    filter_fields = ('is_highpoint',)

    def create(self, request, *args, **kwargs):
        # 添加至热销榜
        goods_list = request.data.get('goods_list')
        for goods_id in goods_list:
            try:
                goods = Goods.objects.filter(id=goods_id, is_delete=False, is_highpoint=False).first()
            except Exception as e:
                return Response(data={'msg': '输入有误/商品不存在/该商品已是高端品'}, status=status.HTTP_204_NO_CONTENT)
            if goods:
                goods.is_highpoint = True
                goods.save()
        return self.list(request)

    def update(self, request, *args, **kwargs):
        # 重写，只能修改is_highpoint字段的值
        is_highpoint = request.data.get('is_highpoint')
        instance = self.get_object()
        instance.is_highpoint = is_highpoint
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        return Response(data={'msg': '操作不允许'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)


class CartOptGoodsViewset(mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
    """购物车商品推荐的可选商品"""
    serializer_class = OptGoodsSerializer
    # 筛选出还没有添加到购物车推荐的商品,包括未推荐的商品
    queryset = Goods.objects.exclude(goods__show_status=1).filter(goods_status=1, is_delete=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
    search_fields = ('name',)

    def create(self, request, *args, **kwargs):
        # 重写
        goods_list = request.data.get('goods_list')
        show_status = request.data.get('show_status')
        for goods in goods_list:
            instance = CartRe.objects.filter(goods=goods).first()
            if instance:
                instance.show_status = show_status
                instance.save()
            else:
                goods = Goods.objects.get(id=goods)
                CartRe.objects.create(goods=goods, show_status=show_status)
        return Response(data={'msg': '保存成功！'}, status=status.HTTP_200_OK)


class CartReViewset(ModelViewSet):
    """购物车商品推荐的是否上线"""
    serializer_class = CartReSerializer
    queryset = CartRe.objects.filter(goods__is_delete=False, goods__goods_status=1)
    pagination_class = GoodsPagination
    permission_classes = (AdminAuth,)

    def update(self, request, *args, **kwargs):
        # 重写，只能修改show_status字段的值
        show_status = request.data.get('show_status')
        instance = self.get_object()
        instance.show_status = show_status
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class GoodsListViewset(BaseViewset):
    """商品列表页"""
    queryset = Goods.objects.filter(is_delete=False, goods_status=1)
    serializer_class = GoodsListSerializer
    pagination_class = GoodsPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('name', 'goods_sn')
    ordering_fields = ('sold_num', 'shop_price')

    def update(self, request, *args, **kwargs):
        # 重写，只能修改goods_status字段的值
        goods_status = request.data.get('goods_status')
        instance = self.get_object()
        if instance.end_time < datetime.date.today() and goods_status == 1:
            return Response(data={'msg': '该商品下架时间已过，如需修改请前往商品详情页重新输入商品上下架时间'})
        instance.goods_status = goods_status
        if goods_status == 0:
            instance.end_time = datetime.date.today()
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class DepotGoodsListViewset(BaseViewset):
    """仓库中的商品列表页"""
    queryset = Goods.objects.filter(is_delete=False, goods_status=0)
    serializer_class = GoodsListSerializer
    pagination_class = GoodsPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('name', 'goods_sn')
    ordering_fields = ('sold_num', 'shop_price')

    def update(self, request, *args, **kwargs):
        # 重写，只能修改goods_status字段的值
        goods_status = request.data.get('goods_status')
        instance = self.get_object()
        instance.goods_status = goods_status
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class GoodsOperateViewset(BaseViewset):
    """商品的增删查改(不含商品属性的添加)"""
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    def list(self, request, *args, **kwargs):
        return Response(data={'不允许访问！'}, status=status.HTTP_401_UNAUTHORIZED)


class RelevanceGoodsViewset(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
                            mixins.ListModelMixin,
                            viewsets.GenericViewSet):
    """添加的关联的商品"""
    queryset = Goods.objects.all()
    serializer_class = OptGoodsSerializer
    permission_classes = (AdminAuth,)
    lookup_field = "goods_id"

    def modify_is_delete_attr(self, obj, value):
        """
        :param obj: 分别传入的商品属性，商品轮播，商品详情类的is_delete属性
        :return:
        """
        for single in obj:
            single.is_delete = value
            single.save()
        return

    def create(self, request, *args, **kwargs):
        goods_id = request.data.get('goods_id')
        goods_list = request.data.get('goods_list')
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        is_delete = request.data.get('is_delete')
        instance = self.queryset.filter(id=goods_id).first()
        if goods_list:
            for goods in goods_list: instance.relevance_goods.add(goods)
        instance.is_delete = is_delete
        instance.start_time = start_time
        instance.end_time = end_time
        instance.save()
        # 把商品轮播图is_delete改回False
        goods_banners = GoodsBannerImage.objects.filter(goods=instance)
        self.modify_is_delete_attr(goods_banners, is_delete)
        # 把商品详情图is_delete改回False
        goods_descs = GoodsDescImage.objects.filter(goods=instance)
        self.modify_is_delete_attr(goods_descs, is_delete)
        # 把商品属性的is_delete改回False
        goods_attribute = GoodsAttribute.objects.filter(goods=instance)
        self.modify_is_delete_attr(goods_attribute, is_delete)
        serializer = self.get_serializer(instance)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        goods_id = self.kwargs.get("goods_id")
        instance = self.queryset.get(id=goods_id)
        relevance_goods = instance.relevance_goods.all()
        serializer = self.get_serializer(relevance_goods, many=True)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        goods_id = self.kwargs.get("goods_id")
        goods_list = request.data.get("goods_list")
        instance = self.queryset.get(id=goods_id)
        instance.relevance_goods.clear()
        for goods in goods_list:
            instance.relevance_goods.add(goods)
        instance.save()
        relevance_goods = instance.relevance_goods.all()
        serializer = self.get_serializer(relevance_goods, many=True)
        return Response(serializer.data)

    def list(self, request, *args, **kwargs):
        goods_id = int(request.query_params.get("goods_id"))
        instance = self.queryset.exclude(id=goods_id, is_delete=True)
        serializer = self.get_serializer(instance, many=True)
        return Response(serializer.data)


class GoodsProViewset(ModelViewSet):
    """商品属性，轮播图，详情图基类视图"""
    lookup_field = 'goods_id'
    permission_classes = (AdminAuth,)

    def list(self, request, *args, **kwargs):
        return Response(data={'不允许访问！'}, status=status.HTTP_401_UNAUTHORIZED)

    def retrieve(self, request, *args, **kwargs):
        goods_id = self.kwargs.get("goods_id")
        instance = self.queryset.filter(goods=goods_id)
        serializer = self.get_serializer(instance, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(data={'msg': '添加成功！'}, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        # 修改功能：先删除后创建
        goods_id = self.kwargs.get("goods_id")
        instance_list = self.queryset.filter(goods=goods_id)
        instance_list.delete()
        return self.create(request)


class GoodsAttributeViewset(GoodsProViewset):
    """商品属性的增删查改"""
    queryset = GoodsAttribute.objects.filter(is_delete=False)
    serializer_class = GoodsAttributeSerializer

    def destroy(self, request, *args, **kwargs):
        # 软删除,删除后订单记录还有记录
        instance = self.get_object()
        instance.is_delete = True
        instance.save()
        return Response(data={'msg': '删除成功！'}, status=status.HTTP_204_NO_CONTENT)

    def update(self, request, *args, **kwargs):
        # 修改功能：先删除后创建
        goods_id = self.kwargs.get("goods_id")
        attr_list = self.queryset.filter(goods=goods_id)
        for attr in attr_list:
            attr.is_delete = True
            attr.save()
        return self.create(request)


class GoodsBannerImgViewset(GoodsProViewset):
    """商品详情页轮播图的增删查改"""
    # queryset = GoodsBannerImage.objects.filter(is_delete=False)
    queryset = GoodsBannerImage.objects.all()
    serializer_class = GoodsBannerImageSerializer

    def update(self, request, *args, **kwargs):
        # 修改功能：先删除后创建
        goods_id = request.data.get('goods_id')
        banner_list = request.data.get('banner_list')
        if not all([goods_id, banner_list]):
            return Response(data={'msg': '缺少参数！'})
        goods = Goods.objects.get(id=int(goods_id))
        queryset = self.queryset.filter(goods=goods)
        if queryset.count() >= 1:
            queryset.delete()
        return self.create(request)


class GoodsDescImgViewset(GoodsProViewset):
    """商品详情页详情图的增删查改"""
    # queryset = GoodsDescImage.objects.filter(is_delete=False)
    queryset = GoodsDescImage.objects.all()
    serializer_class = GoodsDescImageSerializer

    def update(self, request, *args, **kwargs):
        # 修改功能：先删除后创建
        goods_id = request.data.get('goods_id')
        desc_list = request.data.get('desc_list')
        if not all([goods_id, desc_list]):
            return Response(data={'msg': '缺少参数！'})
        goods = Goods.objects.get(id=int(goods_id))
        queryset = self.queryset.filter(goods=goods)
        if queryset.count() >= 1:
            queryset.delete()
        return self.create(request)


# 启动项目后开启定时工作.每天检测商品上下架时间
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

try:
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # 设置定时任务，另一种方式为方式为interval，时间间隔为10s
    # 每天固定时间执行任务，对应代码为：
    goods_scan_time = "商品上下架扫描时间" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    discount_scan_time = "优惠套餐上下架扫描时间" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    create_goods_scan_time = "创建商品时丢弃数据删除扫描时间" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    today = datetime.date.today()


    @register_job(scheduler, 'cron', day_of_week='mon-sun', hour='00', minute='00', second='00', id=goods_scan_time)
    # @register_job(scheduler, "interval", seconds=10)
    def modify_goods_status():
        print('商品上下架扫描时间任务开启', datetime.datetime.now())
        from goods.models import Goods
        # 获取当天要上架的商品
        goods_list = Goods.objects.filter(start_time=today, is_delete=False)
        for goods in goods_list:
            if goods.end_time <= today: continue
            goods.goods_status = 1
            goods.save()
        # 获取当天要下架的商品
        Goods.objects.filter(end_time=today).update(goods_status=0)


    @register_job(scheduler, 'cron', day_of_week='mon-sun', hour='00', minute='00', second='00', id=discount_scan_time)
    def modify_discount_status():
        # 定时修改套餐的状态
        print('优惠套餐扫描时间任务开启', datetime.datetime.now())
        discounts = DiscountPackage.objects.filter(start_time=today, is_delete=False)
        for discount in discounts:
            if discount.end_time <= today: continue
            discount.is_valid = True
            discount.save()
        DiscountPackage.objects.filter(end_time=today).update(is_valid=False)
        # 如果套餐中有一个或多个商品下架，那么该套餐失效
        discounts = DiscountPackage.objects.all()
        for i in discounts:
            for j in i.goods.all():
                # 如果当前时间在套餐的有效期内，那么该套餐生效
                if i.start_time <= today <= i.end_time:
                    i.is_valid = True
                    i.save()
                # 如果套餐中有一个或多个商品下架或者超出活动时间，那么该套餐失效
                if j.goods_status == 0 or (today >= i.end_time):
                    i.is_valid = False
                    i.save()


    @register_job(scheduler, 'cron', day_of_week='mon-sun', hour='01', minute='00', second='00',
                  id=create_goods_scan_time)
    # @register_job(scheduler, "interval", seconds=10)
    def modify_goods_status():
        print('废弃商品扫描时间任务开启', datetime.datetime.now())
        from goods.models import Goods
        # 获取当天要上架废弃的商品
        goods_list = Goods.objects.filter(is_delete=True)
        for goods in goods_list:
            if goods.start_time == None or goods.end_time == None:
                goods.delete()


    register_events(scheduler)
    scheduler.start()
except Exception as e:
    print(e)
    scheduler = BackgroundScheduler()
    scheduler.start()
